Laravel / Advanced / Email using sendgrid API
Email using sendgrid
-
STEPS
1. mail class
namespace App\Mails; class Email { public $data; public function __construct($data) { $this->data = $data; } public static function send($data) { $content = $data['content']; $data['email_from'] = "crm@appsline.in"; $data['email_bcc']="manojvijayanaluva@gmail.com"; $personalized['to'][]=['email' => $data['email_to']]; if(isset($data['email_bcc'])){ $data['email_bcc']=explode(",", $data['email_bcc']); foreach($data['email_bcc'] as $val){ $personalized['bcc'][]=['email' => $val]; } } if(isset($data['email_cc'])){ $data['email_cc']=explode(",", $data['email_cc']); foreach($data['email_cc'] as $val){ $personalized['cc'][]=['email' => $val]; } } $postData= [ 'personalizations' => [ $personalized ], 'from' => [ 'email' => $data['email_from'], ], 'subject' => $data['subject'], 'content' => [ [ 'type' => 'text/html', 'value' => $content, ] ] ]; $postData=json_encode($postData); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"https://api.sendgrid.com/v3/mail/send"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); //Post Fields curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $headers = [ 'Authorization: Bearer SG.ogOyQR19SKiertert2gIBV_A.t4retertertertersjghRpXduCLGrjo8rAQ', 'Content-Type: application/json' ]; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $server_output = curl_exec ($ch); //print_R($server_output);exit; curl_close ($ch); } } 2. controller
use App\Mails\Email; $content['email_to']="manoj@gmail.com"; $data['content'] = view('emails.order_template', $content)->render(); Email::send($data); 1. Email is the class in App\Mails\Email,php
2. 'emails.order_template' is blade file. Path is resources/views/emails/order_template.blade.php
3. view() is used for loading the blade
4. render() is used instead of return for getting the content of the blade
3. create blade for mail template
resources/views/emails/order_template.blade.php